package game

import (
	"fmt"
	"gmanager/app/constants"
	"gmanager/app/service/paycenter"
	"gmanager/app/utils"
	"gmanager/library/base"

	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

// 充值界面
func Recharge(r *ghttp.Request) {
	// 用户基本请求
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	// 支付方式
	channels, err := g.DB().Table("game_pay_channel").Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).OrderBy("sort asc").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(channels) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is empty",
		})
	}
	// 查询该用户记录
	user, err := g.DB().Table("user").Where("id", r.GetString("uid")).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if user == nil || len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 商品
	shops, err := g.DB().Table("charge_item").OrderBy("index asc").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	r.Response.WriteJson(g.Map{
		"code": 0,
		"msg":  "success",
		"data": g.Map{
			"user":     user,
			"shops":    shops,
			"channels": channels,
		},
	})
}

// 用户选择支付金额和支付方式
func RechargeChannel(r *ghttp.Request) {
	var req *paycenter.RechargeChannelReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 查询该用户记录
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "User is not found",
		})
	}
	// 商品
	shop, err := g.DB().Table("charge_item").Where("id", r.GetString("shop_id")).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(shop) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Product is not found",
		})
	}
	// 支付方式
	channel, err := g.DB().Table("game_pay_channel").Where("id", req.ChannelID).Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(channel) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is not found",
		})
	}

	// 用户所有绑定的记录
	rows, err := paycenter.GetUserAllBindFields(req.Uid, req.AppID, req.ChannelID, constants.PAY_MODE_PAY)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
		"data": g.Map{
			"user":            user,
			"shop":            shop,
			"channel":         channel,
			"all_bind_fields": rows,
		},
	})
}

// 用户填写没有填的字段
func RechargeBindField(r *ghttp.Request) {
	var req *paycenter.RechargeChannelReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	mapFields := r.Get("map")
	if mapFields == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Map fields is empty",
		})
	}

	// 用户
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	for k, v := range mapFields.(map[string]interface{}) {
		g.DB().Table("game_pay_user_field_rel").Data(g.Map{
			"pay_user_id":  user["id"],
			"pay_field_id": k,
			"value":        v,
		}).Save()
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
	})
}

// 用户充值下单
func RechargeOrder(r *ghttp.Request) {
	var req *paycenter.RechargeOrderReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 没有绑定的记录
	rows, err := paycenter.GetUserNotBindFields(req.Uid, req.AppID, req.ChannelID, constants.PAY_MODE_PAY)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(rows) > 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "You should complete profile",
		})
	}
	// 商品
	shop, err := g.DB().Table("charge_item").Where("id", req.ShopID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(shop) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Product is not found",
		})
	}
	// 支付方式
	channel, err := g.DB().Table("game_pay_channel").Where("id", req.ChannelID).Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).One()
	if err != nil {
		r.Response.WriteTpl("payement_error.html", g.Map{
			"err": err,
		})
		return
	}
	if len(channel) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is not found",
		})
	}
	// 用户
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	// 下单
	paycenter.PayementOrder(user, shop, channel, r)
}

// 钱包首页
func Index(r *ghttp.Request) {
	// 签名
	// if paycenter.RechargeCheckSign(r.GetMap()) == false {
	// 	r.Response.WriteJsonExit(g.Map{
	// 		"code": -1,
	// 		"msg":  "Sign is error",
	// 	})
	// }
	// 用户基本请求
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 支付方式
	channels, err := g.DB().Table("game_pay_channel").Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).OrderBy("sort asc").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(channels) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is empty",
		})
	}
	// 配置参数
	respData := gmap.New()
	gamePayConfs, err := g.DB().Table("sys_config").Where("category", "game_pay").Where("enable", 1).All()
	for _, conf := range gamePayConfs {
		if conf["key"].String() == "withdraw_fee" || conf["key"].String() == "first_recharge_discount" || conf["key"].String() == "edit_profile_reward" || conf["key"].String() == "withdraw_limit_min" {
			respData.Set(conf["key"].String(), conf["value"].String())
		}
	}
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	respData.Set("uid", user["id"].String())
	respData.Set("money", user["money"].String())
	respData.Set("bonus_money", user["bonus_money"].String())
	respData.Set("channels", channels)
	respData.Set("is_edit_profile", user["is_edit_profile"])
	respData.Set("is_charge", user["is_charge"])
	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
		"data": respData,
	})
}

// 提现
func Withdraw(r *ghttp.Request) {
	// 用户基本请求
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	// 支付方式
	channels, err := g.DB().Table("game_pay_channel").Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).OrderBy("sort asc").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(channels) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is empty",
		})
	}
	// 查询该用户记录
	user, err := g.DB().Table("user").Where("id", req.Uid).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if user == nil || len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 商品
	shops, err := g.DB().Table("charge_item").OrderBy("index asc").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 配置参数
	respData := gmap.New()
	gamePayConfs, err := g.DB().Table("sys_config").Where("category", "game_pay").Where("enable", 1).All()
	for _, conf := range gamePayConfs {
		if conf["key"].String() == "withdraw_fee" || conf["key"].String() == "first_recharge_discount" || conf["key"].String() == "edit_profile_reward" || conf["key"].String() == "withdraw_limit_min" {
			respData.Set(conf["key"].String(), conf["value"].String())
		}
	}
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	r.Response.WriteJson(g.Map{
		"code": 0,
		"msg":  "success",
		"data": g.Map{
			"user":               user,
			"shops":              shops,
			"channels":           channels,
			"withdraw_fee":       respData.Get("withdraw_fee"),
			"withdraw_limit_min": respData.Get("withdraw_limit_min"),
		},
	})

}

// 商户提现可用余额
func WithdrawBalance(r *ghttp.Request) {
	// 查询可用的支付渠道
	payconfID := r.GetString("conf_id")
	model := g.DB().Table("game_pay_conf").Where("status", constants.PAY_CONF_STATUS_OPEN)
	if payconfID != "" {
		model.Where("id", payconfID)
	}
	payconfs, err := model.All()

	// 没有渠道就返回
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	// 获取商户提现可用余额
	result, err := paycenter.GetBalance(payconfs)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "成功",
		"data": result,
	})

}

// 订单查询
func Query(r *ghttp.Request) {
	orderID := r.GetString("order_id")
	if orderID == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "订单号必传",
		})
	}
	// 验证渠道
	payconfID := r.GetString("conf_id")
	if payconfID == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "渠道ID必传",
		})
	}

	// 查询对应的请求记录
	record, err := g.DB().Table("game_try_record").Where("order_id", orderID).Where("conf_id", payconfID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if record == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "该订单在请求记录中查询不到",
		})
	}

	// 查询可用的支付渠道
	payconf, err := g.DB().Table("game_pay_conf").Where("id", payconfID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if payconf == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "该渠道配置查找不到",
		})
	}

	// 获取商户提现可用余额
	result, err := paycenter.GetQuery(payconf)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
		"data": result,
	})
}

// 支付回调通知
func PayNotify(r *ghttp.Request) {
	// 验证渠道
	payconfID := r.GetString("confID")
	if payconfID == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "ConfID is empty",
		})
	}
	// 查询可用的支付渠道
	payconf, err := g.DB().Table("game_pay_conf").Where("id", payconfID).Fields("params,name as conf_name,id").One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if payconf == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payconf is empty",
		})
	}

	paycenter.NotifyPay(payconf, r)

}

func DrawNotify(r *ghttp.Request) {
	// 验证渠道
	payconfID := r.GetString("confID")
	if payconfID == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "ConfID is empty",
		})
	}
	// 查询可用的支付渠道
	payconf, err := g.DB().Table("game_pay_conf").Where("id", payconfID).Fields("*,name as conf_name").One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if payconf == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payconf is empty",
		})
	}

	paycenter.NotifyDraw(payconf, r)

}

// 个人信息
func Profile(r *ghttp.Request) {
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 查询该用户记录
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if user == nil || len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 查询库里的所有字段
	fields, err := g.DB().Table("game_pay_field").All()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 查询该用户已填写的字段
	userFields, err := paycenter.GetUserFieldsValue(user["id"].Int())
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	// 将用户的字段赋值到系统的所有字段
	lists := g.List{}
	for _, f := range fields {
		item := g.Map{
			"descript": f["descript"],
			"id":       f["id"],
			"name":     gstr.UcFirst(f["name"].String()),
			"type":     f["type"],
			"value":    "",
		}
		for _, uf := range userFields {
			if f["id"].Int() == uf["pay_field_id"].Int() {
				item["value"] = uf["value"].String()
				break
			}
		}

		lists = append(lists, item)
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
		"data": g.Map{
			"user":        user,
			"user_fields": lists,
		},
	})
}

// 编辑个人信息
func EditProfile(r *ghttp.Request) {
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	mapFields := r.GetMapStrStr()
	if mapFields == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Map fields is empty",
		})
	}
	err := paycenter.EditProfile(req.Uid, req.AppID, mapFields)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
	})
}

// 提现记录
func WithdrawRecord(r *ghttp.Request) {
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	form := base.NewForm(r.GetQueryMap())
	model := g.DB().Table("game_order").Where("uid", req.Uid).Where("pay_mode", constants.PAY_MODE_DRAW).Where("app_id", req.AppID)
	count, err := model.Count()
	rows, err := model.OrderBy("id desc").Page(form.Page, form.Rows).Select()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	r.Response.WriteJson(g.Map{
		"code":     0,
		"msg":      "success",
		"total":    count,
		"page":     form.Page,
		"pagesize": form.Rows,
		"data":     rows,
	})
}

// 客户反馈
func FeedBack(r *ghttp.Request) {
	var req *paycenter.UserReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	content := r.GetString("content")
	if content == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Content is required",
		})
	}

	g.DB().Table("game_pay_feedback").Data(g.Map{
		"channel": req.AppID,
		"uid":     req.Uid,
		"content": content,
	}).Insert()

	r.Response.WriteJson(g.Map{
		"code": 0,
		"msg":  "success",
	})
}

// 用户选择了提现渠道后
func WithdrawChannel(r *ghttp.Request) {
	var req *paycenter.RechargeChannelReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	money := r.GetString("money")
	if money == "" {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Withdraw money is required",
		})
	}

	// 查询该用户记录
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "User is not found",
		})
	}
	// 支付方式
	channel, err := g.DB().Table("game_pay_channel").Where("id", req.ChannelID).Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(channel) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is not found",
		})
	}

	// 没有绑定的记录
	rows, err := paycenter.GetUserAllBindFields(req.Uid, req.AppID, req.ChannelID, constants.PAY_MODE_DRAW)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
		"data": g.Map{
			"user":            user,
			"money":           money,
			"channel":         channel,
			"all_bind_fields": rows,
		},
	})
}

// 用户填写未绑定的提现字段
func WithdrawBindField(r *ghttp.Request) {
	var req *paycenter.RechargeChannelReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	mapFields := r.Get("map")
	if mapFields == nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Map fields is empty",
		})
	}

	// 用户
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}

	for k, v := range mapFields.(map[string]interface{}) {
		g.DB().Table("game_pay_user_field_rel").Data(g.Map{
			"pay_user_id":  user["id"],
			"pay_field_id": k,
			"value":        v,
		}).Save()
	}

	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
	})
}

// 用户提现下单
func WithdrawUserOrder(r *ghttp.Request) {
	var req *paycenter.RechargeChannelReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 没有绑定的记录
	rows, err := paycenter.GetUserNotBindFields(req.Uid, req.AppID, req.ChannelID, constants.PAY_MODE_DRAW)
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(rows) > 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "You should complete profile",
		})
	}

	// 支付方式
	channel, err := g.DB().Table("game_pay_channel").Where("id", req.ChannelID).Where("enabled", constants.PAY_CHANNEL_STATUS_OPEN).One()
	if err != nil {
		r.Response.WriteTpl("payement_error.html", g.Map{
			"err": err,
		})
		return
	}
	if len(channel) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Payement is not found",
		})
	}
	// 用户
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	if len(user) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err,
		})
	}
	gamePayConfs := utils.GetSystemConfig("game_pay")
	// 商品
	money := r.GetInt64("money")
	// 最小金额判定
	limitMinWithdraw := utils.GetSystemConfigByKey(gamePayConfs, "withdraw_limit_min")
	if gconv.Int64(money) < limitMinWithdraw.Int64() {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "The minimum withdrawal amount is " + limitMinWithdraw.String(),
		})
	}

	// 手续费
	feeRate := utils.GetSystemConfigByKey(gamePayConfs, "withdraw_fee")
	fee := gconv.Float64(money) * (gconv.Float64(feeRate) / 100)

	// 当前提现是否超出额度
	fmt.Println((gconv.Float64(money) + gconv.Float64(fee)), (user["money"].Float64() - user["bonus_money"].Float64()))
	if (gconv.Float64(money) + gconv.Float64(fee)) > (user["money"].Float64() - user["bonus_money"].Float64()) {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "Excess of available amount",
		})
	}

	_, err = g.DB().Table("game_order").Data(g.Map{
		"app_id":       req.AppID,
		"uid":          req.Uid,
		"money":        r.GetFloat64("money"),
		"order_id":     utils.GetOrderNo(constants.PAY_MODE_DRAW_TYPE),
		"pay_mode":     constants.PAY_MODE_DRAW,
		"status":       constants.ORDER_STATE_ONGOING,
		"channel_id":   channel["id"],
		"channel_name": channel["name"],
		"fee":          fee,
	}).Insert()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	// 通知游戏冻结金额
	utils.PushChangeUserMoney(gconv.Int(req.Uid), -(r.GetFloat64("money") + gconv.Float64(fee)), 0)
	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
	})

}

// 后台提现下单
func WithdrawOrder(r *ghttp.Request) {
	// 签名
	// if paycenter.RechargeCheckSign(r.GetMap()) == false {
	// 	r.Response.WriteJsonExit(g.Map{
	// 		"code": -1,
	// 		"msg":  "Sign is error",
	// 	})
	// }
	var req *paycenter.WithdrawOrderReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 获取订单
	order, err := g.DB().Table("game_order").Where("order_id", req.OrderID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if len(order) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "订单不存在",
		})
	}

	// 状态校验
	// if order["status"].Int() != constants.ORDER_STATE_ONGOING {
	// 	r.Response.WriteJsonExit(g.Map{
	// 		"code": -1,
	// 		"msg":  "订单状态已变更",
	// 	})
	// }

	// 获取用户
	user, err := g.DB().Table("user").Where("id", req.Uid).Where("channel", req.AppID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if len(order) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "用户不存在",
		})
	}

	// 获取支付通道
	conf, err := g.DB().Table("game_pay_conf").Where("id", r.GetString("conf_id")).Fields("*,name as conf_name").One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if len(conf) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "支付通道不存在",
		})
	}

	paycenter.WithdrawOrder(user, order, conf, r)
}

// 后台拒绝下单
func RejectWithdrawOrder(r *ghttp.Request) {
	var req *paycenter.WithdrawOrderReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}

	// 修改订单记录
	order, err := g.DB().Table("game_order").Where("order_id", req.OrderID).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if len(order) == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "订单不存在",
		})
	}
	result, err := g.DB().Table("game_order").Data(g.Map{
		"status": constants.ORDER_STATE_FAIL,
		"msg":    r.GetString("remark"),
	}).Where("status!=?", constants.ORDER_STATE_FAIL).Where("order_id", req.OrderID).Update()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	updateResult, err := result.RowsAffected()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  err.Error(),
		})
	}
	if updateResult <= 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": -1,
			"msg":  "拒绝失败",
		})
	}
	// 给用户把钱加回去
	utils.PushChangeUserMoney(gconv.Int(req.Uid), order["money"].Float64()+order["fee"].Float64(), 0)
	r.Response.WriteJsonExit(g.Map{
		"code": 0,
		"msg":  "success",
	})

}
